package com.brian.mongo.controller;

import com.brian.mongo.domain.User;
import com.brian.mongo.exception.UserNotFoundException;
import com.brian.mongo.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-05-16 11:36
 **/

@RestController
public class UserAuthController {

    static final long EXPIRATION_TIME = 30000;

    Map<String,String> map = new HashMap<>();

    private UserService userService;

    public UserAuthController(UserService userService) {
        this.userService = userService;
    }


    @PostMapping("/login")
    public ResponseEntity<?> doLogin(@RequestBody User user){

        String jwtToken = "";

        try {
            jwtToken = generateJwtToken(user.getUsername(),user.getPassword());
            map.put("message","Login in success~");
            map.put("token",jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
            map.put("message",e.getMessage());
            map.put("token",null);
            return new ResponseEntity<>(map,HttpStatus.UNAUTHORIZED);
        }

        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    private String generateJwtToken(String username, String password) throws Exception{
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new ServletException("Not provide the username or password!");
        }

        boolean flag = userService.validateUser(username, password);
        if(!flag){
            throw new UserNotFoundException();
        }

       String jwtToken =  Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256,"secretkey")
                .compact();


        return jwtToken;
    }
}
